/**
 * 
 */
package com.sto.stoapp.http;

import android.util.Log;

import com.sto.stoapp.log.ExceptionLog;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class HttpManager {
	private boolean needSubstring = true;

	public void setNeeSubstring(boolean needSubstring) {
		this.needSubstring = needSubstring;
	}

	@SuppressWarnings("deprecation")
	public String doPostClient(String json, String url) {
		HttpClient httpClient = new HttpClient();
		String rval = "";
		PostMethod postMethod = null;
		InputStream in = null;
		try {
			postMethod = new PostMethod(url);
			byte[] bytes;
			System.out.println("发送：" + json);
			bytes = objectToByte(json);
			String s = new String(bytes);
			in = new ByteArrayInputStream(bytes);
			postMethod.setRequestBody(in);
			HttpClientParams params = new HttpClientParams();
			params.setConnectionManagerTimeout(5000);
			params.setSoTimeout(1 * 60 * 1000);
			httpClient.setParams(params);
			httpClient.executeMethod(postMethod);

			byte[] b = postMethod.getResponseBody();
			rval = (String) byteToObject(b);
			System.out.println("收到：" + rval);
			if (needSubstring)
				rval = rval.substring(6, rval.length());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (postMethod != null)
				postMethod.releaseConnection();

		}

		return rval;
	}

	private byte[] objectToByte(java.lang.Object obj) {
		byte[] bytes = null;
		ByteArrayOutputStream out = null;
		GZIPOutputStream gzip = null;
		try {
			out = new ByteArrayOutputStream();
			// 使用默认缓冲区大小创建新的输出流
			gzip = new GZIPOutputStream(out);
			// 将 b.length 个字节写入此输出流
			gzip.write(obj.toString().getBytes());
			gzip.close();
			bytes = out.toByteArray();

		} catch (Exception e) {

			System.out.println("translation" + e.getMessage());
			e.printStackTrace();
			if (gzip != null) {
				try {
					gzip.close();
				} catch (IOException e2) {
					e.printStackTrace();
				}
			}
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return bytes;
	}

	private java.lang.Object byteToObject(byte[] bytes) {
		java.lang.Object obj = null;
		ByteArrayOutputStream out = null;
		ByteArrayInputStream bi = null;
		GZIPInputStream gzip = null;
		try {
			byte[] byteT = new byte[2];
			byteT[0] = bytes[0];
			byteT[1] = bytes[1];
			int i = getShort(byteT);
			if (i != 0x1f8b) {
				ExceptionLog.writeLog("byteToObject",
						"not use GZIPInputStream:" + i + "--"
								+ new String(bytes));

			}
			out = new ByteArrayOutputStream();
			bi = new ByteArrayInputStream(bytes);
			gzip = new GZIPInputStream(bi);
			int count;
			byte data[] = new byte[1024];
			while ((count = gzip.read(data, 0, 1024)) != -1) {
				out.write(data, 0, count);
				out.flush();
			}
			obj = out.toString("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (gzip != null) {
				try {
					gzip.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bi != null) {
				try {
					bi.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {

					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return obj;
	}

	private String getJsonStringFromGZIP(HttpResponse response) {
		String jsonString = null;
		try {
			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is);
			bis.mark(2);
			// 取前两个字节
			byte[] header = new byte[2];
			int result = bis.read(header);
			// reset输入流到开始位置
			bis.reset();
			// 判断是否是GZIP格式
			int headerData = getShort(header);
			// Gzip 流 的前两个字节是 0x1f8b
			if (result != -1 && headerData == 0x1f8b) {
				ExceptionLog.writeLog("getJsonStringFromGZIP",
						"use GZIPInputStream");
				is = new GZIPInputStream(bis);
			} else {
				ExceptionLog.writeLog("getJsonStringFromGZIP",
						"not use GZIPInputStream");
				is = bis;
			}
			InputStreamReader reader = new InputStreamReader(is, "utf-8");
			char[] data = new char[100];
			int readSize;
			StringBuffer sb = new StringBuffer();
			while ((readSize = reader.read(data)) > 0) {
				sb.append(data, 0, readSize);
			}
			jsonString = sb.toString();
			bis.close();
			reader.close();
		} catch (Exception e) {
			ExceptionLog.writeLog("getJsonStringFromGZIP", e.toString());
		}
		System.out.println("getJsonStringFromGZIP收到：" + jsonString);
		return jsonString;
	}

	private int getShort(byte[] data) {
		return (int) ((data[0] << 8) | data[1] & 0xFF);
	}

	/**
	 * HttpClient的Get请求方法
	 * Add by wj
	 */
	public String doGetClient(String url){

		if(url==null){
			return null;
		}

		url=url.replace(" ", "%20");
		Log.e("wj","请求地址:"+url);

		HttpClient httpClient = new HttpClient();
		String rval = "";
		GetMethod getMethod = null;
		InputStream in = null;
		try {
			getMethod = new GetMethod(url);

			HttpClientParams params = new HttpClientParams();
			params.setConnectionManagerTimeout(5000);
			params.setSoTimeout(1 * 60 * 1000);
			httpClient.setParams(params);
			int statusCode=httpClient.executeMethod(getMethod);

			if (statusCode != HttpStatus.SC_OK) {
				Log.e("wj","error:"+statusCode);
				return null;
			}

			byte[] b = getMethod.getResponseBody();
			rval = new String(b);
			Log.e("wj","收到:"+rval);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (getMethod != null)
				getMethod.releaseConnection();

		}

		return rval;
	}

	public String doPostClientBy(String url,String content){
		String strResult = null;
		HttpPost httpRequest =new HttpPost(url);
		try{
			StringEntity myEntity = new StringEntity(content,"utf-8");
			httpRequest.setEntity(myEntity);
			HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
			//若状态码为200 ok
			if(httpResponse.getStatusLine().getStatusCode()==200){
				strResult= EntityUtils.toString(httpResponse.getEntity());
			}
			else
			{
				Log.v("tag", "Error Response"+httpResponse.getStatusLine().toString() );
			}
		}catch(ClientProtocolException e){
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return strResult;

	}

	/**
	 * 发送post请求
     */
	public static String doPost(String url,ArrayList<NameValuePair> pairs){

		org.apache.http.client.HttpClient httpClient=new DefaultHttpClient();
		BufferedReader reader=null;
		try {
			HttpPost httpPost = new HttpPost(url);
			//创建代表请求体的对象（注意，是请求体）
			HttpEntity requestEntity = new UrlEncodedFormEntity(pairs);
			//将请求体放置在请求对象当中
			httpPost.setEntity(requestEntity);
			//第三步：执行请求对象，获取服务器发还的相应对象
			HttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
					//第五步：从相应对象当中取出数据，放到entity当中
				HttpEntity entity = response.getEntity();
				reader = new BufferedReader(
					new InputStreamReader(entity.getContent()));
				String result = reader.readLine();
				Log.d("HTTP", "POST:" + result);
				return result;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(null!=reader){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return null;
	}
}
